﻿using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Reflection;

namespace SCS.Web.UI.WebControls.Dialogs.Test
{
    // Class courtesy Scott Guthrie. http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx
    //
    public class HtmlBuilder
    {
        public static string RenderView(string path)
        {
            return RenderUserControl(path, null);
        }

        public static string RenderUserControl(string path, string contextKey)
        {
            Page pageHolder = new Page();
            UserControl viewControl = (UserControl)pageHolder.LoadControl(path);

            if (contextKey != null)
            {
                Type viewControlType = viewControl.GetType();
                FieldInfo field = viewControlType.GetField("ContextKey");

                if (field != null)
                {
                    field.SetValue(viewControl, contextKey);
                }
                else
                {
                    throw new Exception("View file: " + path + " does not have a public Data property");
                }
            }

            pageHolder.Controls.Add(viewControl);

            StringWriter output = new StringWriter();
            HttpContext.Current.Server.Execute(pageHolder, output, false);

            return output.ToString();
        }
    }
}
